package com.topvision.myviewtest.surface.camera;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.YuvImage;
import android.hardware.Camera;

import com.topvision.myviewtest.surface.util.FileUtil;
import com.topvision.myviewtest.surface.util.ImageUtil;

import java.io.ByteArrayOutputStream;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Author: lucy
 * Comment: //TODO
 * Date: 2017-11-16 10:50
 */

public class CameraPreviewCallback implements Camera.PreviewCallback {

    private final ExecutorService mThreadExecutor;
    private final MyRunnable mRunnable;

    public CameraPreviewCallback(Camera camera) {
        mThreadExecutor = Executors.newSingleThreadExecutor();
        mRunnable = new MyRunnable(camera);
    }

    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        mThreadExecutor.execute(mRunnable.setData(data));
    }

    class MyRunnable implements Runnable {
        private Random mRandom;
        private byte[] mData;
        private int i;
        private Camera mCamera;
        public MyRunnable(Camera camera) {
            mCamera = camera;
            mRandom = new Random();

        }

        @Override
        public synchronized void run() {
            //处理data操作
            byte[] data = getRawData(mCamera, mData);
            Bitmap b = null;
            if (null != data) {
                b = BitmapFactory.decodeByteArray(data, 0, data.length);
            }
            if (null != b) {
                Bitmap rotaBitmap = ImageUtil.getRotateBitmap(b, 90.0f);
                FileUtil.saveBitmap(rotaBitmap);
            }
            i++;
            System.out.println("保存成功:" + i);
        }

        public MyRunnable setData(byte[] data) {
            mData = data;
            return this;
        }
    }

    private byte[] getRawData(Camera camera, byte[] data) {
        Camera.Size previewSize = camera.getParameters().getPreviewSize();
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        newOpts.inJustDecodeBounds = true;
        YuvImage yuvimage = new YuvImage(
                data,
                ImageFormat.NV21,
                previewSize.width,
                previewSize.height,
                null);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // JPG图片的质量[0-100],100最高
        yuvimage.compressToJpeg(new android.graphics.Rect(0, 0, previewSize.width, previewSize.height), 80, baos);
        return baos.toByteArray();
    }

}
